//
//  YXAddBankCardTableView.m
//  CreditCard
//
//  Created by 杨旭 on 2017/12/23.
//  Copyright © 2017年 杨旭. All rights reserved.
//

#import "YXAddBankCardTableView.h"
#import "YXAddPartnerTableView.h"
@interface YXAddBankCardTableView ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic ,strong) NSArray *titleArr;
@property (nonatomic ,strong) NSArray *contentArr;
@property (nonatomic ,strong) UIButton *codeBtn;
@property (nonatomic ,strong) UIView *headerView;
@property (nonatomic ,strong) UIView *footerView;
@property (nonatomic ,strong) UIButton *addBtn;
@end

@implementation YXAddBankCardTableView

- (NSArray *)titleArr {
    if (!_titleArr) {
        _titleArr = @[@"持卡人",@"卡号",@"银行预留手机",@"验证码"];
    }
    return _titleArr;
}

- (NSArray *)contentArr {
    if (!_contentArr) {
        _contentArr = @[[YXUserInfoManager getUserInfo].name,@"请输入卡号",@"请输入手机号",@"请输入验证码"];
    }
    return _contentArr;
}

- (UIView *)headerView {
    if (!_headerView) {
        _headerView = [[UIView alloc] initWithFrame:(CGRectMake(0, 0, kScreenWidth, 50))];
        _headerView.backgroundColor = [UIColor whiteColor];
        
        UIButton *radioBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
        radioBtn.frame = CGRectMake(0, 0, kScreenWidth, 50);
        radioBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        [radioBtn setImage:[UIImage imageNamed:@"喇叭"] forState:(UIControlStateNormal)];
        [radioBtn setTitle:@"为了保障资金安全，请绑定认证本人银行卡" forState:(UIControlStateNormal)];
        [radioBtn setTitleColor:color_globalColor forState:(UIControlStateNormal)];
        radioBtn.imageEdgeInsets = UIEdgeInsetsMake(0, -10, 0, 0);
        [_headerView addSubview:radioBtn];
        
        UIView *lineView1 = [[UIView alloc] initWithFrame:(CGRectMake(0, 0, kScreenWidth, 1))];
        lineView1.backgroundColor = color_lineColor;
        [_headerView addSubview:lineView1];
        
        UIView *lineView2 = [[UIView alloc] initWithFrame:(CGRectMake(0, _headerView.H - 1, kScreenWidth, 1))];
        lineView2.backgroundColor = color_lineColor;
        [_headerView addSubview:lineView2];
    }
    return _headerView;
}


- (UIButton *)codeBtn {
    if (!_codeBtn) {
        _codeBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
        _codeBtn.backgroundColor = color_globalColor;
        _codeBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        [_codeBtn setTitle:@"获取验证码" forState:(UIControlStateNormal)];
        [_codeBtn setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
        _codeBtn.layer.masksToBounds = YES;
        _codeBtn.layer.cornerRadius = 8;
        [_codeBtn addTarget:self action:@selector(codeBtnAction:) forControlEvents:(UIControlEventTouchUpInside)];
    }
    return _codeBtn;
}

- (void)codeBtnAction:(UIButton *)sender {
    UITextField *tf1 = [self viewWithTag:3002];
    NSString *str = [self valiMobile:tf1.text];
    
    if(str) {
        [self showTostMessage:str];
    }else {
        //      http://121.196.210.134:8082/mpos/wx/sendBankSmsCode.do
        NSString *urlStr = @"sendBankSmsCode.do";
        NSDictionary *parameter = @{@"phone":tf1.text};
        [BX_NetWorkManager requestForPOSTWithUrl:urlStr parameter:parameter success:^(id responseObject) {
            if (REQUESTDATASUCCESS) {
                [self GCDTime];
                [self showAlertWithTitle:@"提示" Messge:@"手机短信发送成功！"];
            }
        } failure:^(NSError *error) {
            [self showAlertWithTitle:@"提示" Messge:@"维护中，请稍等！"];

        }];
    }
   
}


- (UIView *)footerView {
    if (!_footerView) {
        _footerView = [[UIView alloc] initWithFrame:(CGRectMake(0, 0, kScreenWidth, kScreenHeight -  self.titleArr.count * 50-15))];
        [_footerView addSubview:self.addBtn];
    }
    return _footerView;
}

- (UIButton *)addBtn {
    if (!_addBtn) {
        _addBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
        _addBtn.frame = CGRectMake(20, 40, kScreenWidth - 40, 50);
        _addBtn.layer.masksToBounds = YES;
        _addBtn.layer.cornerRadius = 8.0f;
        _addBtn.backgroundColor = [UIColor py_colorWithHexString:@"#CBCCCD"];
        _addBtn.userInteractionEnabled =NO;
        [_addBtn setTitle:@"添加" forState:(UIControlStateNormal)];
        [_addBtn setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
        [_addBtn addTarget:self action:@selector(addPartnerBtnAction:) forControlEvents:(UIControlEventTouchUpInside)];
        
    }
    return _addBtn;
    
}

- (void)addPartnerBtnAction:(UIButton *)sender {
    
    UITextField *tf1 = [self viewWithTag:3001];
    UITextField *tf2 = [self viewWithTag:3002];
    UITextField *tf3 = [self viewWithTag:3003];
    
    if (tf1.text.length == 0 || tf2.text.length == 0 || tf3.text.length == 0) {
        [self showTostMessage:@"请填写完整信息！"];
    }else {
        NSDictionary *dict = @{@"bankNo":tf1.text,@"phone":tf2.text,@"vCode":tf3.text};
        if (self.addBankCardBlock) {
            self.addBankCardBlock(dict);
        }
    }
}


- (instancetype)initWithFrame:(CGRect)frame style:(UITableViewStyle)style {
    if (self = [super initWithFrame:frame style:style]) {
        self.backgroundColor = color_backColor;
        self.separatorStyle = UITableViewCellSeparatorStyleNone;
        self.dataSource = self;
        self.delegate = self;
        self.contentInset = UIEdgeInsetsMake(15, 0, 0, 0);
        self.tableHeaderView = self.headerView;
        self.tableFooterView = self.footerView;
        [self registerClass:[YXAddPartnerTableViewcell class] forCellReuseIdentifier:@"YXAddPartnerTableViewcell"];
    }
    return self;
}

#pragma mark - UITableView Delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.titleArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    YXAddPartnerTableViewcell *cell = [tableView dequeueReusableCellWithIdentifier:@"YXAddPartnerTableViewcell" forIndexPath:indexPath];
    cell.titleLab.text = self.titleArr[indexPath.row];
    cell.contentTF.placeholder = self.contentArr[indexPath.row];
    cell.contentTF.tag = indexPath.row + 3000;
    cell.contentTF.keyboardType = UIKeyboardTypeNumberPad;
    if (indexPath.row == 0) {
        cell.contentTF.enabled = NO;
    }
    
    if (indexPath.row == 3) {
        [cell.contentView addSubview:self.codeBtn];
        __weak typeof (cell) weakSelf = cell;
        [_codeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(weakSelf.mas_centerY);
            make.right.equalTo(weakSelf.mas_right).offset(-10);
            make.size.mas_equalTo(CGSizeMake(100, 36));
        }];
        
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 50;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    YXAddPartnerTableViewcell *cell = [tableView cellForRowAtIndexPath:indexPath];
    [cell.contentTF becomeFirstResponder];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    UITextField *tf1 = [self viewWithTag:3001];
    UITextField *tf2 = [self viewWithTag:3002];
    UITextField *tf3 = [self viewWithTag:3003];
    [tf1 resignFirstResponder];
    [tf2 resignFirstResponder];
    [tf3 resignFirstResponder];

}

//制作timeButton的属性文本
- (NSMutableAttributedString *)makeTimeButtonAttributed:(NSInteger)time{
    NSMutableAttributedString *string3 = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"%li",time] attributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]}];
    NSMutableAttributedString *string4 = [[NSMutableAttributedString alloc]initWithString:@"剩余" attributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]}];
    
    [string4 insertAttributedString:string3 atIndex:string4.length];
    return string4;
}
#pragma mark - time
- (void)GCDTime{
    
    __block NSInteger time = 60;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
    dispatch_source_set_event_handler(timer, ^{
        if (time < 1) {
            dispatch_source_cancel(timer);
            NSMutableAttributedString *string = [[NSMutableAttributedString alloc]initWithString:@"重新发送" attributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]}];
            dispatch_async(dispatch_get_main_queue(), ^{
                _codeBtn.userInteractionEnabled = YES;
                [_codeBtn setAttributedTitle:string forState:(UIControlStateNormal)];
                _codeBtn.backgroundColor = color_globalColor;
            });
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                _codeBtn.userInteractionEnabled = NO;
                _codeBtn.backgroundColor = [UIColor py_colorWithHexString:@"#CBCCCD"];
                [_codeBtn setAttributedTitle:[self makeTimeButtonAttributed:time] forState:(UIControlStateNormal)];
                _addBtn.backgroundColor = color_globalColor;
                _addBtn.userInteractionEnabled = YES;
                
            });
            time --;
        }
    });
    dispatch_resume(timer);
}


@end
